<template>
  <div class="tab-content-container user-profile-form">
    <h3 class="section-title">基本资料</h3>

    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
      status-icon
      v-loading="loading"
    >
      <el-form-item label="用户名" prop="name">
        <el-input style="margin-right: 300px;" v-model="form.name" placeholder="请输入用户名" />
      </el-form-item>

      <el-form-item label="院系" prop="department">
        <el-select
        style="margin-right: 300px;"
          v-model="form.department"
          placeholder="请选择院系"
          :loading="loadingDepartments"
        >
          <el-option
            v-for="dept in departments"
            :key="dept.id"
            :label="dept.name"
            :value="dept.name"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="班级" prop="class">
        <el-input style="margin-right: 300px;" v-model="form.class" placeholder="请输入班级" />
      </el-form-item>

      <el-form-item label="电子邮箱" prop="email">
        <el-input style="margin-right: 300px;" v-model="form.email" placeholder="请输入电子邮箱" />
      </el-form-item>

      <el-form-item label="手机号码" prop="phone">
        <el-input style="margin-right: 300px;" v-model="form.phone" placeholder="请输入手机号码" />
      </el-form-item>

      <el-form-item label="个人简介" prop="bio">
        <el-input
        style="margin-right: 300px;"
          v-model="form.bio"
          type="textarea"
          :rows="3"
          placeholder="请输入个人简介"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm" :loading="submitting"
          >保存更改</el-button
        >
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from "vue";
import { ElMessage } from "element-plus";
import api from "@/utils/api";

export default {
  name: "UserProfileForm",
  props: {
    userInfo: {
      type: Object,
      required: true,
    },
  },
  emits: ["update"],
  setup(props, { emit }) {
    const formRef = ref(null);
    const loading = ref(false);
    const submitting = ref(false);
    const departments = ref([]);
    const loadingDepartments = ref(false);

    const form = reactive({
      name: "",
      department: "",
      class: "",
      email: "",
      phone: "",
      bio: "",
    });

    const rules = {
      name: [
        { required: true, message: "请输入用户名", trigger: "blur" },
        { min: 2, max: 20, message: "长度在 2 到 20 个字符", trigger: "blur" },
      ],
      department: [
        // 保持原有规则
      ],
      class: [
        // 保持原有规则
      ],
      email: [
        // 移除必填规则，仅保留格式验证
        { type: "email", message: "请输入正确的邮箱地址", trigger: "blur" },
      ],
      phone: [
        // 保持原有规则，如果有的话
        {
          pattern: /^1[3-9]\d{9}$/,
          message: "请输入正确的手机号码",
          trigger: "blur",
        },
      ],
      bio: [
        // 移除必填规则，仅保留长度验证（如果有的话）
        { max: 200, message: "个人简介不能超过200个字符", trigger: "blur" },
      ],
    };

    // 从API获取用户信息
    const fetchUserProfile = async () => {
      loading.value = true;
      try {
        const response = await api.get(`/user/profile`);
        if (response.data.code === 200) {
          const userData = response.data.data;
          // 更新表单数据
          form.name = userData.username || "";
          form.department = userData.department || "";
          form.class = userData.clazz || "";
          form.email = userData.email || "";
          form.phone = userData.phone || "";
          form.bio = userData.bio || "";
        } else {
          ElMessage.error(response.data.message || "获取用户资料失败");
          // 回退到props中的用户信息
          initForm();
        }
      } catch (error) {
        console.error("获取用户资料失败:", error);
        ElMessage.error("获取用户资料失败，请稍后再试");
        // 回退到props中的用户信息
        initForm();
      } finally {
        loading.value = false;
      }
    };

    const initForm = () => {
      form.name = props.userInfo.name || "";
      form.department = props.userInfo.department || "";
      form.class = props.userInfo.class || "";
      form.email = props.userInfo.email || "";
      form.phone = props.userInfo.phone || "";
      form.bio = props.userInfo.bio || "";
    };

    const submitForm = async () => {
      if (!formRef.value) return;

      try {
        const valid = await formRef.value.validate();
        if (valid) {
          submitting.value = true;

          try {
            const response = await api.put("/user/profile", {
              username: form.name,
              department: form.department,
              class: form.class,
              email: form.email,
              phone: form.phone,
              bio: form.bio,
            });

            if (response.data.code === 200) {
              ElMessage.success("个人资料更新成功");
              // 向父组件发送更新事件，不包含name字段
              emit("update", {
                // 不包含 name 字段
                department: form.department,
                class: form.class,
                email: form.email,
                phone: form.phone,
                bio: form.bio,
              });
            } else {
              ElMessage.error(response.data.message || "更新个人资料失败");
            }
          } catch (error) {
            console.error("更新个人资料失败:", error);
            ElMessage.error("更新个人资料失败，请稍后再试");
          } finally {
            submitting.value = false;
          }
        }
      } catch (error) {
        ElMessage.error("请检查表单填写是否正确");
      }
    };

    const resetForm = async () => {
      if (!formRef.value) return;

      try {
        submitting.value = true;
        // 调用重置接口，只保留用户名
        const response = await api.post("/user/profile/reset", {
          preserveFields: ["name"], // 指定要保留的字段
        });

        if (response.data.code === 200) {
          ElMessage.success("资料已重置，用户名已保留");
          // 重新获取用户资料
          fetchUserProfile();
          // 重置表单验证状态
          formRef.value.resetFields();
        } else {
          ElMessage.error(response.data.message || "重置失败");
        }
      } catch (error) {
        console.error("重置用户资料失败:", error);
        ElMessage.error("重置失败，请稍后再试");
        // 如果重置失败，至少清除当前表单的修改
        formRef.value.resetFields();
        fetchUserProfile();
      } finally {
        submitting.value = false;
      }
    };

    // 获取院系列表
    const fetchDepartments = async () => {
      loadingDepartments.value = true;
      try {
        const response = await api.get("/departments");
        if (response.data.code === 200) {
          departments.value = response.data.data;
        } else {
          ElMessage.warning("获取院系列表失败，请稍后再试");
        }
      } catch (error) {
        console.error("获取院系列表失败:", error);
        ElMessage.warning("获取院系列表失败，请稍后再试");
      } finally {
        loadingDepartments.value = false;
      }
    };

    onMounted(() => {
      // 先用传入的用户信息初始化表单
      initForm();
      // 获取最新的用户信息
      fetchUserProfile();
      // 获取院系列表
      fetchDepartments();
    });

    return {
      formRef,
      form,
      rules,
      loading,
      submitting,
      submitForm,
      resetForm,
      departments,
      loadingDepartments,
    };
  },
};
</script>

<style scoped>
.user-profile-form {
  width: 800px !important; /* 固定宽度 */
}

.section-title {
  width: 100%;
  margin-top: 0;
  margin-bottom: 20px;
  color: var(--text-primary);
  font-size: 18px;
  border-bottom: 1px solid var(--border-color);
  padding-bottom: 10px;
}

/* 确保表单元素宽度一致 */
:deep(.el-form-item) {
  width: 100%;
}

:deep(.el-form-item__content) {
  width: 600px !important;
}

:deep(.el-input),
:deep(.el-select),
:deep(.el-textarea) {
  width: 100% !important;
}
</style> 